package institutional

import inscription.InscriptionCourse
import org.springframework.dao.DataIntegrityViolationException
import user.Student
import org.apache.shiro.SecurityUtils;

/**
 * CourseController
 * A controller class handles incoming web requests and performs actions such as redirects, rendering views and so on.
 */
class CourseController {
	
	
	static scaffold = true
    static allowedMethods = [save: "POST", update: "POST", delete: "POST"]
	def studentService
	
    def index() {
        redirect(action: "list", params: params)
    }

    def list() {
        params.max = Math.min(params.max ? params.int('max') : 10, 100)
		
		if (params.subjectId != null) {
			def subjectInstance = Subject.get(params.subjectId)
			def courseList = Course.findAll{subject.id== subjectInstance.id  && available}
			[courseInstanceList: courseList, courseInstanceTotal: courseList.size()]
		}
		else
			[courseInstanceList: Course.list(params), courseInstanceTotal: Course.count()]
    }

    def create() {
        [courseInstance: new Course(params)]
    }

    def save() {
        def courseInstance = new Course(params)
        if (!courseInstance.save(flush: true)) {
            render(view: "create", model: [courseInstance: courseInstance])
            return
        }

		flash.message = message(code: 'default.created.message', args: [message(code: 'course.label', default: 'Course'), courseInstance.id])
        redirect(action: "show", id: courseInstance.id)
    }

    def show() {
        def courseInstance = Course.get(params.id)
        if (!courseInstance) {
			flash.message = message(code: 'default.not.found.message', args: [message(code: 'course.label', default: 'Course'), params.id])
            redirect(action: "list")
            return
        }

        [courseInstance: courseInstance]
    }

    def edit() {
        def courseInstance = Course.get(params.id)
        if (!courseInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'course.label', default: 'Course'), params.id])
            redirect(action: "list")
            return
        }

        [courseInstance: courseInstance]
    }

    def update() {
        def courseInstance = Course.get(params.id)
        if (!courseInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'course.label', default: 'Course'), params.id])
            redirect(action: "list")
            return
        }

        if (params.version) {
            def version = params.version.toLong()
            if (courseInstance.version > version) {
                courseInstance.errors.rejectValue("version", "default.optimistic.locking.failure",
                          [message(code: 'course.label', default: 'Course')] as Object[],
                          "Another user has updated this Course while you were editing")
                render(view: "edit", model: [courseInstance: courseInstance])
                return
            }
        }

        courseInstance.properties = params

        if (!courseInstance.save(flush: true)) {
            render(view: "edit", model: [courseInstance: courseInstance])
            return
        }

		flash.message = message(code: 'default.updated.message', args: [message(code: 'course.label', default: 'Course'), courseInstance.id])
        redirect(action: "show", id: courseInstance.id)
    }

    def delete() {
        def courseInstance = Course.get(params.id)
        if (!courseInstance) {
			flash.message = message(code: 'default.not.found.message', args: [message(code: 'course.label', default: 'Course'), params.id])
            redirect(action: "list")
            return
        }

        try {
            courseInstance.delete(flush: true)
			flash.message = message(code: 'default.deleted.message', args: [message(code: 'course.label', default: 'Course'), params.id])
            redirect(action: "list")
        }
        catch (DataIntegrityViolationException e) {
			flash.message = message(code: 'default.not.deleted.message', args: [message(code: 'course.label', default: 'Course'), params.id])
            redirect(action: "show", id: params.id)
        }
    }
	
	
	def createInscriptionToCourse() {
		
		def studentInstance = Student.findByStudentId(SecurityUtils.getSubject().principal)
		
		if (!studentInstance) {
			flash.message = message(code: 'default.not.found.message', args: [message(code: 'student.label', default: 'Student'), params.id])
			redirect(uri: "home/index")
			return
		}
		
		if (!studentInstance.save(flush: true)) {
			render(view: "create", model: [studentInstance: studentInstance])
			return
		}
		
		def courseInstance = Course.get(params.courseId)
		int inscriptionToCourse = studentService.enrolStudentToCourse (studentInstance, courseInstance)
		if (inscriptionToCourse != 0 ) {
			if (inscriptionToCourse == 1) {
				flash.message = message([code: 'course.inscription.not.opened.message', default: "Inscription is not opened"])
			}
			else if (inscriptionToCourse == 2) {
				flash.message = message([code: 'course.not.space.message', default: "The course is full"])
			}
			else if (inscriptionToCourse == 3) {
				flash.message = message([code: 'course.not.space.message', default: "Student reach maximun number of inscriptions "])
			}
			else if (inscriptionToCourse == 4) {
				flash.message = message([code: 'course.not.in.majors.message', default: "This subject is not available for your majors"])
			}
			else if (inscriptionToCourse == -1) {
				flash.message = message([code: 'course.error.saving.message', default: "Could not save in database"])
			}
			redirect(controller: "student", action: "listEnroledCourses", params:[id: studentInstance.id])
			return
		}

		redirect(controller: "student", action: "listEnroledCourses", params:[id: studentInstance.id])
		return
	}
	
	
}
